<template>
  <el-dialog v-model="centerDialogVisible" title="查询信息" width="80%" center draggable :modal="!hotMapVisible">
    <el-table :data="displayData" style="width: 100%">
      <el-table-column v-for="(value, key) in query_result[0]" :key="key" :prop="key" :label="key" width="auto" />
    </el-table>
    <el-pagination background layout="prev, pager, next" :total="query_result.length" :page-size="pageSize"
      @current-change="handleCurrentChange" />
    <el-dialog v-model="innerVisible" style="width: 80%" title="事件统计" center append-to-body>
      <el-segmented v-model="Chartvalue" :options="ChartType" />
      <div style="display: flex" v-if="renderChartFlag">
        <template v-if="Chartvalue === 'line'">
          <el-radio-group v-model="radio" vertical>
            <el-radio-button label="月统计" value="month" />
            <el-radio-button label="年统计" value="year" />
          </el-radio-group>
          <div style="width: 100%; height: 400px">
            <v-chart :option=lineData></v-chart>
          </div>
        </template>
        <template v-else>
          <div style="width: 100%; height: 400px">
            <v-chart :option="PieChart"></v-chart>
          </div>
        </template>
      </div>
    </el-dialog>
    <el-dialog v-model="hotMapVisible" style="width: 50%" title="热力图" center append-to-body destroy-on-close
      :modal="!hotMapVisible" draggable :close-on-click-modal="false" v-if="heatMapFlag">
      <div>
        <label>热点半径(Radius size):</label>
        <el-slider v-model="Radiusvalue" :max="maxRadius" :format-tooltip="formatRadius" @input="updateRadius" />
      </div>
      <div>
        <label>模糊尺寸(Blur size):</label>
        <el-slider v-model="Blurvalue" :max="maxBlur" :format-tooltip="formatBlur" @input="updateBlur" />
      </div>
    </el-dialog>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="danger" @click="handleClose" :icon="CircleClose">退出</el-button>
        <el-button type="primary" @click="exportToExcel" :icon="Printer"> 数据导出 </el-button>
        <el-button type="primary" @click="handleInnerVisible"> 事件统计 </el-button>
        <el-button type="primary" @click="handleHotMapVisible"> 热力图 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineExpose, nextTick, watch, getCurrentInstance, computed } from 'vue'
import { useCommonStore } from '@/stores/common'
import { storeToRefs } from 'pinia'
import * as XLSX from 'xlsx';
import FileSaver from 'file-saver';
import { CircleClose,Printer } from '@element-plus/icons-vue'
import { addQueryDraw } from './hook/queryDraw.js'
import { renderChart, LineChartMonth, LineChartYear, PieChart } from './hook/queryChart.js'
// const emits = defineEmits(['close'])
// import { geoJson } from './hook/queryDraw.js'
import { ToFeature } from '@/hook/ol-api/index.js'

const {
  activeDraw,
  handleCurrentChange,
  cancelQuery,
  handleClose,
  query_result,
  pageSize,
  displayData,
  centerDialogVisible,
  Radiusvalue,
  maxRadius,
  Blurvalue,
  maxBlur,
  updateRadius,
  updateBlur
} = addQueryDraw()
defineExpose({
  activeDraw,
  cancelQuery
})

/* 引入公共状态管理对象 */
const store = useCommonStore()
const { renderChartFlag, heatMapFlag } = storeToRefs(store)
const innerVisible = ref(false)
watch(innerVisible, (newVal) => {
  renderChartFlag.value = false
})
const handleInnerVisible = () => {
  innerVisible.value = true
  nextTick(() => {
    // console.log(query_result.value)
    renderChart(query_result.value)
  })
}

/**监控热力图弹窗的显示
 * 当热力图弹窗显示时，将centerDialogVisible置为false，防止用户点击热力图弹窗时，弹窗消失
 * 当热力图弹窗消失时，将centerDialogVisible置为true，恢复用户点击查询弹窗时，弹窗的显示
 */
const { proxy } = getCurrentInstance()
let heatMap = proxy.$map
const hotMapVisible = ref(false)
const handleHotMapVisible = () => {
  hotMapVisible.value = true
  centerDialogVisible.value = false
  heatMapFlag.value = true
  heatMap.getLayers().forEach(layer => {
    if (layer.get('name') === '热力图') {
      layer.setVisible(true);
    }
  })
}
watch(hotMapVisible, (newVal) => {
  if (!newVal && !centerDialogVisible.value) {
    centerDialogVisible.value = true
  }
})

/** 热力图相关 */
const formatRadius = (value) => `当前半径:${value}`
const formatBlur = (value) => `当前模糊尺寸:${value}`

const ChartType = [
  {
    label: '事件统计折线图',
    value: "line"
  },
  {
    label: '事件统计饼图',
    value: "pie"
  }
]
const Chartvalue = ref(ChartType[0].value)
const radio = ref('month')
const lineData = computed(() => {
  if (radio.value === 'month') {
    return LineChartMonth
  } else {
    return LineChartYear
  }
})

const columnData = ref([])


watch(query_result, (newVal) => {
  if (newVal.length > 0) {
    columnData.value = Object.keys(newVal[0]).map(key => {
      return {
        prop: key,
        label: key
      }
    })
  }
})
// 导出
const exportToExcel = () => {
  
  let newTableData = resetTableData()
  const worksheet = XLSX.utils.json_to_sheet(newTableData);
		const workbook = XLSX.utils.book_new()
		XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
  const excelBuffer = XLSX.write(workbook, {
			bookType: 'xlsx',
			type: 'array'
		});
		// 将缓冲区转换为 Blob 并保存为文件
		const data = new Blob([excelBuffer], {
			type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
		});
		FileSaver.saveAs(data, 'tableData.xlsx');
	}
 
	const resetTableData = () => {
		const propToLabelMap = new Map(columnData.value.map(item => [item.prop, item.label]));
		const restructuredTableData = []
		query_result.value.map(row => {
			// 使用映射表创建新对象，其中键为label值，值为原对象的相应prop值
			const newRow = {};
			for (const prop in row) {
				if (row.hasOwnProperty(prop) && propToLabelMap.has(prop)) {
					newRow[propToLabelMap.get(prop)] = row[prop];
				}
			}
			restructuredTableData.push(newRow)
		})
		return restructuredTableData

}
</script>

<style scoped>
.el-segmented{
  margin-bottom: 10px;
}
.el-radio-group {
  position: absolute;
  right: 10px;
  top: 30%;
  z-index: 999;
}
.el-radio-button:first-child {
  position: absolute;
  top: 40px;
  z-index: 999;
}
</style>
